﻿/*************************************************************************************
 * 工    具：  HK_CSharpInspector
 * 
 * 描    述：  本工具用于增强 Inspector 面板中代码预览显示功能，主要功能如下：
 *             代码重新格式化：调整预览代码的词间距，使代码布局更加美观，便于开发者快速浏览和理解代码结构。
 *             行号显示：在代码左侧显示行号，方便开发者快速定位代码行，提升调试效率。
 *             字体优化：使用 Fira Code 等宽字体，提供更好的代码预览体验，确保字符间距一致，提升可读性。
 *             动态主题适配：根据Unity编辑器主题设定，分为浅色和深色主题，模仿 Visual Studio 的主题风格，对 C# 的关键字、常见类、常见结构体、自定义方法等进行颜色高亮，提升代码的可读性和可视化效果。
 *             动态主题自定义配置：在 HKTools/HK_InspectorProSettings/CSharpPreviewConfig 菜单中，可自定义关键词高亮的颜色。
 * 
 * 版    本：  V1.9
 * 作    者：  京产肠饭、谭潇杰
 * 
 * 创    建：  2024/09/21  V1.0
 * 
 * 更    新：  2024/09/22  V1.1
 *            1.Bug修复：先保护字符串和注释的内容，防止字符串和注释中的关键字和常用类名被错误着色
 *            2.功能新增：新增常见结构体着色
 *            
 *            2024/09/30  V1.2
 *            1.Bug修复：修复新建脚本时，EditorStyles 初始化失败报空的Bug（似乎用了一个笨方法）
 *            
 *            2024/09/30  V1.3
 *            1.功能新增：关键字渲染区分蓝色和紫色，模仿Visual Studio主题
 *            2.功能新增：根据Unity编辑的主题（深色、浅色），初始化不同的模板着色
 *            3.功能新增：增加行号显示，模仿Visual Studio
 *            
 *            2024/10/01  V1.4
 *            1.性能优化：增加缓存机制（cachedCode），优化代码绘制性能
 *            2.功能优化：优化行号和代码区域的绘制
 *            3.功能优化：渲染字体设定为 FiraCode 等宽字体（开源免费），优化代码预览体验
 *            4.功能新增：Inspector中渲染的代码，支持选中及复制
 *            
 *            2024/11/02  V1.5
 *            1.Bug修复：通过添加零宽度空格，打断原本脚本中的富文本标签，修复代码中原有富文本标签而渲染冲突的Bug
 *            2.性能优化：合并关键字的正则表达式，优化正则表达式性能
 *            
 *            2025/01/03  V1.6
 *            1.Bug修复：适配不同DPI显示器，统一绘制行号及代码的高度
 *            2.性能优化：关键词等正则表达式查询时，使用HashSet替代List，提高查询性能
 *
 *            2025/02/14  V1.7
 *            1.Bug修复：优化源代码富文本标签替换逻辑，修复代码中原有富文本标签而渲染冲突的Bug
 *
 *            2025/03/30  V1.8
 *            1.功能新增：支持自定义类名的高亮显示
 *            2.功能新增：支持自定义方法名的高亮显示
 *            3.功能优化：补充常见类名、结构体名、关键字的高亮显示
 *            4.性能优化：正则表达式优化，优化代码绘制性能
 *
 *            2025/04/04  V1.9
 *            1.性能优化：对正则表达式进行预编译，优化代码绘制性能
 *            2.功能新增：增加颜色主题配置文件，支持自定义颜色，可在HKTools/HK_InspectorProSettings/CSharpPreviewConfig 窗口中进行修改
 * 
 * 链    接：  https://gitee.com/JingChanChangFan/hk_-unity-tools
*************************************************************************************/

using UnityEngine;
using UnityEditor;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Text;

namespace HKTools
{
    /// <summary>
    /// Inspecotr 扩展1：对C#脚本的显示增强
    /// </summary>
    [CustomEditor(typeof(MonoScript))]
    public class HK_CSharpInspector : Editor
    {
        const string DEFAULT_CONFIG_PATH = "Assets/HKTools/ForEditor/4.3HK_InspectorPro/Editor/Resources/";

        // 定义合并后的正则表达式模式  
        static readonly Regex syntaxHighlightRegex;

        static readonly Regex methodRegex = new Regex(
        @"\b(?:(?:public|private|protected|internal|static|virtual|override)\s+)?([\w<>]+)\s+([A-Za-z_]\w*)\s*\(",
        RegexOptions.Compiled);

        static readonly Regex stringLiteralRegex = new Regex(@"@?""([^""]|"""")*""|'(\\.|[^'\\])'", RegexOptions.Compiled);
        static readonly Regex multiLineCommentRegex = new Regex(@"/\*.*?\*/", RegexOptions.Singleline | RegexOptions.Compiled);
        static readonly Regex singleLineCommentRegex = new Regex(@"//.*?$", RegexOptions.Multiline | RegexOptions.Compiled);

        static HK_CSharpInspector()
        {
            string keywordBluePattern = @"\b(" + string.Join("|", keywords_Blue) + @")\b";
            string keywordPurplePattern = @"\b(" + string.Join("|", keywords_Purple) + @")\b";
            string classPattern = @"\b(" + string.Join("|", commonClasses) + @")\b";
            string structPattern = @"\b(" + string.Join("|", commonStructs) + @")\b";

            // 合并模式，使用命名组  
            string combinedPattern = string.Join("|", new[]
            {
                $"(?<keywordBlue>{keywordBluePattern})",
                $"(?<keywordPurple>{keywordPurplePattern})",
                $"(?<commonClass>{classPattern})",
                $"(?<commonStruct>{structPattern})"
            });

            syntaxHighlightRegex = new Regex(combinedPattern, RegexOptions.Compiled | RegexOptions.ExplicitCapture);
        }

        // 定义C#关键字列表（蓝色）
        static HashSet<string> keywords_Blue = new HashSet<string>
        {
            "abstract", "as", "base", "bool", "byte",
            "char", "checked", "class", "const", "decimal",
            "delegate", "do", "double", "enum", "event", "explicit", "extern",
            "false", "fixed", "float",  "goto",
            "implicit", "in", "int", "interface", "internal", "is", "lock", "long",
            "namespace", "new", "null", "object", "operator", "out", "override",
            "params", "private", "protected", "public", "readonly", "ref",
            "sbyte", "sealed", "short", "sizeof", "stackalloc", "static", "string",
            "struct", "this", "throw", "true", "typeof", "uint",
            "ulong", "unchecked", "unsafe", "ushort", "using", "virtual", "void",
            "volatile","get","set",
        };

        // 定义C#关键字列表（紫色）
        static HashSet<string> keywords_Purple = new HashSet<string>
        {
            "if","else","else if","for","foreach","while","try","catch","finally","return","continue","break",
            "switch","case","default"
        };

        // 定义常见的C#和Unity类列表  
        static HashSet<string> commonClasses = new HashSet<string>
        {  
            // ======== C# 基础类库 ========
            // 核心类型
            "Type", "Array", "Enum", "ValueType",
            
            // 集合框架
            "List", "Dictionary", "LinkedList", "Queue",
            "Stack", "HashSet", "SortedSet", "SortedDictionary",
            "ObservableCollection", "IEnumerable",
            
            // 异步编程
            "Task",
            
            // IO与序列化
            "File", "Directory", "Path", "Stream",
            "JsonSerializer", "XmlSerializer", "BinaryFormatter",
            
            // 反射与表达式
            "Expression", "TypeInfo", "Assembly",

            // ======== Unity 核心类库 ========
            // 元数据特性
            "SerializeField", "Header", "RequireComponent",
            "DisallowMultipleComponent", "Range", "HideInInspector",
            "CanEditMultipleObjects", "CustomEditor", "Serializable",
            "CustomPropertyDrawer", "MenuItem", "InitializeOnLoad",
            
            // 对象体系
            "GameObject", "Scene", "Object", "Camera", "Transform",
            
            // 组件体系
            "Behaviour", "Component", "MonoBehaviour", "ScriptableObject",
            "Coroutine", "YieldInstruction", "VideoPlayer",
            
            // 物理系统
            "Ray", "Collision", "Trigger", "ForceMode",
            "RigidbodyConstraints", "PhysicsMaterial",
            "RaycastHit", "Collision2D", "Rigidbody2D",
            
            // 动画系统
            "Animation", "AnimationClip", "AnimatorOverrideController",
            "AvatarMask", "StateMachineBehaviour",
            
            // UI系统
            "RectTransform", "CanvasGroup", "ContentSizeFitter",
            "AspectRatioFitter", "LayoutElement", "GridLayoutGroup",
            "ScrollRect", "InputField", "Slider", "Scrollbar",
            "Dropdown", "LayoutRebuilder", "Image", "Button", "GUIStyle",
            "EditorGUIUtility", "EditorGUILayout", "GUILayout",
            "GUI", "EditorGUI", "Toggle", "Text", "RectMask2D",
            "SpriteRenderer", "Sprite",
            
            // 资源管理
            "AssetBundle", "Resources", "Addressables",
            "AssetDatabase", "EditorUtility",
            
            // 图形渲染
            "MaterialPropertyBlock", "Shader", "ComputeShader",
            "RenderTexture", "LightmapSettings",
            "GraphicsSettings", "QualitySettings",
            
            // 输入系统
            "InputAction", "PlayerInput", "InputSystem",
            
            // 导航与AI
            "NavMeshPath", "NavMeshObstacle", "NavMeshLink", "NavMeshAgent",
            
            // 脚本交互
            "SendMessageOptions", "ExecuteInEditMode",
            "ContextMenu", "Gizmo", "Debug",
            
            // 事件系统
            "UnityEvent", "EventSystem", "Input", "Cursor", "Selection",
            
            // 数据容器
            "PlayerPrefs", "JsonUtility"
        };

        // 定义常见的结构体名列表  
        static HashSet<string> commonStructs = new HashSet<string>
        {  
            // 常见的 Unity 结构体名  
            "Vector2", "Vector3", "Vector4", "Quaternion", "Color", "Color32", "Rect", "Bounds", "Mathf",
            "Ray", "Ray2D", "Matrix4x4", "Plane", "RaycastHit", "RaycastHit2D", "LayerMask",
            "AnimationCurve", "Keyframe", "Gradient", "RectInt", "Vector2Int", "Vector3Int", "RangeInt"
        };

        // 定义颜色变量  
        string colorKeywordBlue; // 蓝色关键字  
        string colorKeywordPurple; // 紫色关键字  
        string colorCommonClass;// 常见类名 
        string colorCommonStruct;// 常见结构体名 
        string colorStringLiteral;// 字符串字面量 
        string colorComment; // 墨绿色注释 
        string colorMethod; // 方法名颜色

        HK_CSharpInspectorConfig cofing;

        Vector2 scrollPosition1;
        Vector2 scrollPosition2;

        GUIStyle codeStyle;
        GUIStyle lineNumberStyle;

        string cachedCode;
        string formatCode;

        float codeAreaHeight;
        static StringBuilder lineSB;

        void Awake()
        {
            InitializeColors();
            InitializeGUIStyle();
        }

        public override void OnInspectorGUI()
        {
            // 如果 codeStyle 为空，则重新初始化 codeStyle
            if (codeStyle == null || lineNumberStyle == null)
            {
                InitializeGUIStyle();
            }

            // 如果 codeStyel 为空，则 return
            if (codeStyle == null || lineNumberStyle == null)
                return;

            MonoScript monoScript = (MonoScript)target;

            // 对比缓存代码，仅在变化时，重新格式化
            if (cachedCode != monoScript.text)
            {
                // 对代码进行格式化
                formatCode = FormatCode(monoScript.text);
                cachedCode = monoScript.text;
            }

            // 分割代码为行  
            string[] lines = formatCode.Split(new[] { '\n' });

            codeAreaHeight = 0;
            lineSB = new StringBuilder();

            for (int i = 0; i < lines.Length; i++)
            {
                codeAreaHeight += EditorGUIUtility.singleLineHeight * 0.85f;
                lineSB.Append(i.ToString() + "\n");
            }

            EditorGUILayout.BeginHorizontal();

            DrawLineNumbers(lineSB.ToString(), 32, codeAreaHeight);
            DrawCodeArea(formatCode, EditorGUIUtility.currentViewWidth - 32, codeAreaHeight);

            EditorGUILayout.EndHorizontal();
        }

        /// <summary>
        /// 根据当前编辑器主题，初始化相应着色模板 
        /// </summary>
        public void InitializeColors()
        {
            cofing = Resources.Load<HK_CSharpInspectorConfig>("HK_CSharpInspectorConfig");

            if (cofing == null)
            {
                cofing = CreateInstance<HK_CSharpInspectorConfig>();
                AssetDatabase.CreateAsset(cofing, $"{DEFAULT_CONFIG_PATH}HK_CSharpInspectorConfig.asset");
                AssetDatabase.SaveAssets();
                Debug.Log("创建了 HK_CSharpInspectorConfig");
            }

            bool isDark = EditorGUIUtility.isProSkin;

            colorKeywordBlue = ColorToHexTag(isDark ? cofing.darkKeywordBlue : cofing.lightKeywordBlue);
            colorKeywordPurple = ColorToHexTag(isDark ? cofing.darkKeywordPurple : cofing.lightKeywordPurple);
            colorCommonClass = ColorToHexTag(isDark ? cofing.darkCommonClass : cofing.lightCommonClass);
            colorCommonStruct = ColorToHexTag(isDark ? cofing.darkCommonStruct : cofing.lightCommonStruct);
            colorStringLiteral = ColorToHexTag(isDark ? cofing.darkStringLiteral : cofing.lightStringLiteral);
            colorComment = ColorToHexTag(isDark ? cofing.darkComment : cofing.lightComment);
            colorMethod = ColorToHexTag(isDark ? cofing.darkMethod : cofing.lightMethod);
        }

        // 新增工具方法
        string ColorToHexTag(Color color)
        {
            return $"<color=#{ColorUtility.ToHtmlStringRGBA(color)}>$1</color>";
        }

        /// <summary>
        /// 初始化代码及行号的显示样式
        /// </summary>
        void InitializeGUIStyle()
        {
            // 加载 FiraCode 字体  
            Font font = Resources.Load<Font>("FiraCode-Medium");

            // 如果加载 FiraCode 字体失败，则使用默认字体
            if (font == null)
            {
                font = EditorStyles.label.font;
            }

            // 若 codeStyle 或 lineNumberStyle 初始化失败，则先置空
            try
            {
                codeStyle = new GUIStyle(EditorStyles.label);
                codeStyle.richText = true;
                codeStyle.font = font;
                codeStyle.fontSize = 12;
                codeStyle.wordWrap = false;
                codeStyle.alignment = TextAnchor.UpperLeft;

                // 自定义选中颜色，防止Inspector面板选中时，绘制的脚本变色
                codeStyle.focused.textColor = codeStyle.normal.textColor;
                codeStyle.active.textColor = codeStyle.normal.textColor;
                codeStyle.hover.textColor = codeStyle.normal.textColor;
                codeStyle.onFocused.textColor = codeStyle.normal.textColor;

                lineNumberStyle = new GUIStyle(GUI.skin.label);
                lineNumberStyle.font = font;
                lineNumberStyle.fontSize = 12;
                lineNumberStyle.alignment = TextAnchor.UpperLeft; // 设置文本右对齐
                lineNumberStyle.normal = new GUIStyleState() { textColor = Color.gray };
            }
            catch
            {
                lineNumberStyle = null;
                codeStyle = null;
            }
        }

        /// <summary>
        /// 对脚本代码，进行格式化
        /// </summary>
        string FormatCode(string originalCode)
        {
            // 使用正则表达式匹配所有富文本标签，通过添加零宽度空格，打断原始脚本中的富文本标签  
            originalCode = Regex.Replace(originalCode, @"<\/?[a-zA-Z]+(?:=[^>]+)?>",
                m => $"<\u200B{m.Value.Substring(1)}");

            // 用于存储字符串和注释内容  
            var stringLiterals = new List<string>();
            var singleLineComments = new List<string>();
            var multiLineComments = new List<string>();

            // 提取并保护字符串和字符串  
            originalCode = stringLiteralRegex.Replace(originalCode, match =>
            {
                stringLiterals.Add(match.Value);
                return $"__STRING_LITERAL_{stringLiterals.Count - 1}__";
            });

            // 首先提取并保护多行注释  
            originalCode = multiLineCommentRegex.Replace(originalCode, match =>
            {
                multiLineComments.Add(match.Value);
                return $"__MULTI_LINE_COMMENT_{multiLineComments.Count - 1}__";
            });

            // 然后提取并保护单行注释  
            originalCode = singleLineCommentRegex.Replace(originalCode, match =>
            {
                singleLineComments.Add(match.Value);
                return $"__SINGLE_LINE_COMMENT_{singleLineComments.Count - 1}__";
            });

            // 提取所有自定义类名（排除系统类）
            var customClasses = new HashSet<string>();
            var classMatches = Regex.Matches(originalCode, @"\bclass\s+([^\s:{]+)");
            foreach (Match match in classMatches)
            {
                string className = match.Groups[1].Value;
                if (!commonClasses.Contains(className) && !commonStructs.Contains(className))
                {
                    customClasses.Add(className);
                }
            }

            // 对自定义类名进行着色
            if (customClasses.Count > 0)
            {
                string pattern = $@"\b({string.Join("|", customClasses)})\b";
                originalCode = Regex.Replace(originalCode, pattern,
                    m => colorCommonClass.Replace("$1", m.Value));
            }

            // 提取自定义方法名
            var customMethods = new HashSet<string>();
            var methodMatches = methodRegex.Matches(originalCode);

            foreach (Match match in methodMatches)
            {
                string returnType = match.Groups[1].Value;
                string methodName = match.Groups[2].Value; // 改为使用第二个捕获组
                if (!commonClasses.Contains(methodName) &&
                    !commonStructs.Contains(methodName) &&
                    !keywords_Blue.Contains(methodName) &&
                    !keywords_Purple.Contains(methodName))
                {
                    customMethods.Add(Regex.Escape(methodName));
                }
            }

            // 对方法名着色
            if (customMethods.Count > 0)
            {
                string methodPattern = $@"\b({string.Join("|", customMethods)})\b(?=\s*\()";
                originalCode = Regex.Replace(originalCode, methodPattern,
                    m => colorMethod.Replace("$1", m.Value));
            }

            // 对关键字 进行着色  
            originalCode = syntaxHighlightRegex.Replace(originalCode, match =>
            {
                if (match.Groups["keywordBlue"].Success)
                    return colorKeywordBlue.Replace("$1", match.Value);
                if (match.Groups["keywordPurple"].Success)
                    return colorKeywordPurple.Replace("$1", match.Value);
                if (match.Groups["commonClass"].Success)
                    return colorCommonClass.Replace("$1", match.Value);
                if (match.Groups["commonStruct"].Success)
                    return colorCommonStruct.Replace("$1", match.Value);
                return match.Value;
            });

            // 还原字符串和字符字面量  
            for (int i = 0; i < stringLiterals.Count; i++)
            {
                string coloredString = colorStringLiteral.Replace("$1", stringLiterals[i]);
                originalCode = originalCode.Replace($"__STRING_LITERAL_{i}__", coloredString);
            }

            // 还原多行注释  
            for (int i = 0; i < multiLineComments.Count; i++)
            {
                string coloredMultiLineComment = colorComment.Replace("$1", multiLineComments[i].Trim());
                originalCode = originalCode.Replace($"__MULTI_LINE_COMMENT_{i}__", $"{coloredMultiLineComment}");
            }

            // 还原单行注释
            for (int i = 0; i < singleLineComments.Count; i++)
            {
                string coloredSingleLineComment = colorComment.Replace("$1", singleLineComments[i].Trim());
                originalCode = originalCode.Replace($"__SINGLE_LINE_COMMENT_{i}__", $"{coloredSingleLineComment}");
            }

            return originalCode;
        }

        /// <summary>
        /// 绘制行号
        /// </summary>
        void DrawLineNumbers(string lineArray, float areaWidth, float codeAreaHeight)
        {
            // 创建一个可滚动的文本区域 绘制行号
            EditorGUILayout.BeginVertical(GUILayout.Width(areaWidth));

            scrollPosition1 = EditorGUILayout.BeginScrollView(scrollPosition1);

            EditorGUILayout.LabelField(lineArray, lineNumberStyle, GUILayout.Height(codeAreaHeight));

            EditorGUILayout.EndScrollView();
            EditorGUILayout.EndVertical();
        }

        /// <summary>
        /// 绘制代码
        /// </summary>
        void DrawCodeArea(string formatCode, float areaWidth, float codeAreaHeight)
        {
            // 创建一个可滚动的文本区域 绘制脚本  
            EditorGUILayout.BeginVertical(GUILayout.Width(areaWidth));

            scrollPosition2 = EditorGUILayout.BeginScrollView(scrollPosition2);

            EditorGUILayout.SelectableLabel(formatCode, codeStyle, GUILayout.Height(codeAreaHeight));

            EditorGUILayout.EndScrollView();
            EditorGUILayout.EndVertical();
        }
    }

    public class HK_CSharpInspectorConfigWindow : EditorWindow
    {
        HK_CSharpInspectorConfig config;
        Vector2 scrollPos;
        bool showDarkTheme = true;
        bool showLightTheme = true;

        [MenuItem("HKTools/HK_InspectorProSettings/CSharpPreviewConfig", priority = HK_MenuPriority.HK_HK_InspectorProSettings)]
        static void Init()
        {
            var window = GetWindow<HK_CSharpInspectorConfigWindow>("CSharpPreviewConfig");
            window.minSize = new Vector2(400, 420);
            window.Show();
        }

        void OnEnable()
        {
            // 加载配置文件
            string configPath = "Assets/HKTools/ForEditor/4.3HK_InspectorPro/Editor/Resources/HK_CSharpInspectorConfig.asset";
            config = AssetDatabase.LoadAssetAtPath<HK_CSharpInspectorConfig>(configPath);

            // 如果不存在则创建默认配置
            if (config == null)
            {
                config = CreateInstance<HK_CSharpInspectorConfig>();
                string dirPath = "Assets/HKTools/ForEditor/4.3HK_InspectorPro/Editor/Resources/";

                // 确保目录存在
                if (!AssetDatabase.IsValidFolder(dirPath))
                {
                    System.IO.Directory.CreateDirectory(Application.dataPath + "/../" + dirPath);
                    AssetDatabase.Refresh(); // 强制刷新目录结构
                }

                AssetDatabase.CreateAsset(config, dirPath + "HK_CSharpInspectorConfig.asset");
                AssetDatabase.SaveAssets();
                AssetDatabase.Refresh(); // 新增资源刷新
                Debug.Log($"已创建新配置文件: {dirPath}HK_CSharpInspectorConfig.asset");
            }
        }

        void OnGUI()
        {
            if (config == null) return;

            EditorGUI.BeginChangeCheck();

            scrollPos = EditorGUILayout.BeginScrollView(scrollPos);

            EditorGUILayout.Space();

            // 深色主题配置
            showDarkTheme = EditorGUILayout.Foldout(showDarkTheme, "深色主题配置", true);
            if (showDarkTheme)
            {
                EditorGUILayout.LabelField("深色主题颜色", EditorStyles.boldLabel);
                config.darkKeywordBlue = ColorField("关键字蓝色", config.darkKeywordBlue);
                config.darkKeywordPurple = ColorField("关键字紫色", config.darkKeywordPurple);
                config.darkCommonClass = ColorField("类名颜色", config.darkCommonClass);
                config.darkCommonStruct = ColorField("结构体颜色", config.darkCommonStruct);
                config.darkStringLiteral = ColorField("字符串颜色", config.darkStringLiteral);
                config.darkComment = ColorField("注释颜色", config.darkComment);
                config.darkMethod = ColorField("方法名颜色", config.darkMethod);
            }

            EditorGUILayout.Space();

            // 浅色主题配置
            showLightTheme = EditorGUILayout.Foldout(showLightTheme, "浅色主题配置", true);
            if (showLightTheme)
            {
                EditorGUILayout.LabelField("浅色主题颜色", EditorStyles.boldLabel);
                config.lightKeywordBlue = ColorField("关键字蓝色", config.lightKeywordBlue);
                config.lightKeywordPurple = ColorField("关键字紫色", config.lightKeywordPurple);
                config.lightCommonClass = ColorField("类名颜色", config.lightCommonClass);
                config.lightCommonStruct = ColorField("结构体颜色", config.lightCommonStruct);
                config.lightStringLiteral = ColorField("字符串颜色", config.lightStringLiteral);
                config.lightComment = ColorField("注释颜色", config.lightComment);
                config.lightMethod = ColorField("方法名颜色", config.lightMethod);
            }

            EditorGUILayout.EndScrollView();

            EditorGUILayout.Space();

            // 恢复默认按钮
            if (GUILayout.Button("恢复默认配置", GUILayout.Height(25)))
            {
                if (EditorUtility.DisplayDialog("确认重置", "确定要恢复默认颜色配置吗？当前修改将会丢失。", "确定", "取消"))
                {
                    var defaultConfig = CreateInstance<HK_CSharpInspectorConfig>();

                    // 深色主题
                    config.darkKeywordBlue = defaultConfig.darkKeywordBlue;
                    config.darkKeywordPurple = defaultConfig.darkKeywordPurple;
                    config.darkCommonClass = defaultConfig.darkCommonClass;
                    config.darkCommonStruct = defaultConfig.darkCommonStruct;
                    config.darkStringLiteral = defaultConfig.darkStringLiteral;
                    config.darkComment = defaultConfig.darkComment;
                    config.darkMethod = defaultConfig.darkMethod;

                    // 浅色主题
                    config.lightKeywordBlue = defaultConfig.lightKeywordBlue;
                    config.lightKeywordPurple = defaultConfig.lightKeywordPurple;
                    config.lightCommonClass = defaultConfig.lightCommonClass;
                    config.lightCommonStruct = defaultConfig.lightCommonStruct;
                    config.lightStringLiteral = defaultConfig.lightStringLiteral;
                    config.lightComment = defaultConfig.lightComment;
                    config.lightMethod = defaultConfig.lightMethod;

                    Debug.Log("已恢复默认颜色配置");
                }
            }

            if (EditorGUI.EndChangeCheck())
            {
                EditorUtility.SetDirty(config);
                AssetDatabase.SaveAssets();
                AssetDatabase.Refresh(); // 新增资源刷新
                Debug.Log("配置已保存至磁盘"); // 添加保存日志
            }

            EditorGUILayout.Space();
        }

        Color ColorField(string label, Color color)
        {
            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.LabelField(label, GUILayout.Width(100));
            var newColor = EditorGUILayout.ColorField(color);
            EditorGUILayout.EndHorizontal();
            return newColor;
        }
    }
}